package com.itv.email.pool;

import com.itv.email.bean.EmailClient;
import com.itv.email.bean.EmailInfo;
import com.itv.email.bean.EmailServer;
import com.itv.email.bean.TransportBean;
import com.itv.email.data.ConfUtil;
import org.apache.log4j.Logger;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * User: bjxiajun
 * Date: 14-5-20
 * Time: 下午1:13
 * 发送邮件的工厂
 */
public class SendFactory {
    private static Logger logger = Logger.getLogger(SendFactory.class);
    public int count=0;
    private int clientNum;
    private List<EmailClient> clients;
    int serverCount=1;
    int timeout=6000;
    int asdlCount=1;
    private SendFactory() {
        init();
    }

    private static SendFactory factory = new SendFactory();

    public boolean send(EmailInfo email) {
        EmailClient client = getSendClinet();
        Session session=client.getSession();
        Transport transport=null;
        try {
            transport = session.getTransport();
            MimeMessage message=new MimeMessage(session);
            message.setFrom(new InternetAddress(client.getAddress()));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecAddress()));
            message.setSubject(email.getSubject());
            if ("HTML".equalsIgnoreCase(email.getType())) {
                message.setContent(email.getInfo(), "text/html;charset = utf-8");
            } else {
                message.setText(email.getInfo());
            }
            transport.connect(client.getName(),client.getPwd());
            System.out.println(client.getName()+" start..."+client.getName()+"  "+client.getPwd());
            transport.sendMessage(message, new Address[]{new InternetAddress(email.getRecAddress())});
            count++;
            if(asdlCount%3==0){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1500);
                            ConnectNetWork.cutAdsl("宽带连接");
                            Thread.sleep(2000);
                            ConnectNetWork.connAdsl("宽带连接","020002132648","10567566");
                        } catch (Exception e) {
                            System.out.println("宽带连接失败。");
                        }
                    }
                }).start();
            }
            asdlCount++;
        } catch (Exception e) {
            logger.error("发送邮件异常。"+client.getName()+" "+client.getPwd(), e);
            return false;
        }finally {
            if(transport!=null){
                try {
                    transport.close();
                    Thread.sleep(timeout);
                    timeout+=10;
                    timeout=timeout>15000?6000:timeout;
                } catch (Exception e) {
                    System.out.println("------close error-----------");
                }
            }
        }
        return true;
    }

    private EmailClient getSendClinet() {
        return clients.get(count%clientNum);
    }

    /**
     * 获取发送邮件的工厂
     *
     * @return
     */
    public static SendFactory getInstence() {
        return factory;
    }

    private void init() {
        EmailServer server = new EmailServer();
        server.setAuth(Boolean.parseBoolean(ConfUtil.getPropertie("server.auth." + serverCount % ConfUtil.serverNum)));
        server.setDebug(Boolean.parseBoolean(ConfUtil.getPropertie("server.debug." + serverCount % ConfUtil.serverNum)));
        server.setHost(ConfUtil.getPropertie("server.host." + serverCount % ConfUtil.serverNum));
        server.setProtocol(ConfUtil.getPropertie("server.protocol." + serverCount % ConfUtil.serverNum));
        String domain = ConfUtil.getPropertie("server.domain." + serverCount % ConfUtil.serverNum);
        String pwd = ConfUtil.getPropertie("client.pwd." + serverCount % ConfUtil.serverNum);
        clientNum = Integer.parseInt(ConfUtil.getPropertie("client.num." + serverCount % ConfUtil.serverNum));
        String cAddress = ConfUtil.getPropertie("client.address." + serverCount % ConfUtil.serverNum);
        int suffix = Integer.parseInt(cAddress.substring(3, cAddress.length()));
        String prefix = cAddress.substring(0, 3);
        clients = new ArrayList<EmailClient>(clientNum);
        Session session=getSession(server);
        for (int i = 0; i < clientNum; i++) {
            EmailClient client = new EmailClient();
            client.setAddress(prefix + (suffix + i) + "@" + domain);
            client.setPwd(pwd);
            client.setSession(session);
            clients.add(client);
        }
    }

    private Session getSession(EmailServer server) {
        Properties props = new Properties();
        props.put("mail.debug", server.isDebug());
        props.put("mail.smtp.auth", server.isAuth());
        props.put("mail.host", server.getHost());
        props.put("mail.transport.protocol", server.getProtocol());
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.socketFactory.port", "465");

        Session session = Session.getInstance(props);
        return session;
    }

    public static void main(String[] args) {
        EmailInfo emailInfo = new EmailInfo();
        emailInfo.setInfo("<div>这是一个测试邮件哦</div>");
        emailInfo.setRecAddress("874389288@qq.com");
        emailInfo.setSubject("这是一个测试邮件哦");
        emailInfo.setType("html");
    }
}
